<?php
class VB_Photo_Variants extends VB_Db_Table {
	protected $_name = 'vb_photovariant';

	protected $_primary = 'photovariant_id';

	protected $_rowClass = 'VB_Photo_Variant';

	protected $_referenceMap = array(
		'Foto' => array(
			'columns' => 'foto_id',
			'refTableClass' => 'VB_Fotos',
			'refColumns' => 'foto_id'
		),
	);
	
	public function getVariant(VB_Foto $photo, $ratio, $width) {
		$pvfs = new VB_Photo_Variantfiles();
		$query = $this->select();
		$query->setIntegrityCheck(false);
		$query->from(array('pv' => $this->info('name')), 'pv.*');
		$query->joinLeft(
			array('pvf' =>$pvfs->info('name')),
			'pv.photovariant_id = pvf.photovariant_id AND pvf.width = ' . $width,
			array('width', 'cachename'));
		$query->where('foto_id = ? ', $photo->foto_id);
		$query->where('photovariant_ratio = ?', $ratio);
		$photovariant = $this->fetchRow($query);
		$photo = $photovariant->findParentRow('VB_Fotos');
		if (empty($photovariant->cachename) || !file_exists(PATH.'/web/files/cache/'.$photovariant->cachename) || filesize(PATH.'/web/files/cache/'.$photovariant->cachename) == 0) {
			//create a cachefile
			$image = new General_Image($photo->getFotoPath());
			$photovariantfile = $pvfs->createRow();
			$photovariantfile->photovariant_id = $photovariant->photovariant_id;
			$photovariantfile->expired = time() + 60*60*24*30;
			$photovariantfile->width = $width;
			$photovariantfile->cachename =
				$photovariant->photovariant_filename . '_' . md5($ratio.'-'.$width).
				$image->mimetype2extension('image/jpeg');
			$height = round($width / $ratio);
			$params = array();
			$params['ThumbnailRatio'] = $ratio;
			$cropParam  = explode('_',$photovariant->cropparam);
			if($cropParam[0] == 'top') {
				$params['ThumbnailCropTop'] = $cropParam[1];
			} else {
				$params['ThumbnailCropLeft'] = $cropParam[1];
			}
			$image->ThumbnailCreate($width,$height,$params);
			$image->Save(PATH.'/web/files/cache/'.$photovariantfile->cachename);
			$photovariantfile->save();
			$photovariant->cachename = $photovariantfile->cachename;
			$photovariant->width = $photovariantfile->width;
		}
		return $photovariant;
	}
	

}
?>